import { dbUtils } from '../core'
import type { StoreShopDesk } from '../types'

export const storeShopDeskRepository = {
    upsertBatch(rows: StoreShopDesk[]): void {
        if (!rows || rows.length === 0) return
        dbUtils.transaction(() => {
            const sql = `INSERT INTO store_shop_desk (
                id, name, category_id, parent_id, region_id, shop_id, store_id, server_clerk_id,
                qr_url, type, capacity, sort, status, is_use, is_delete, create_time
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
            )
            ON CONFLICT(id) DO UPDATE SET
                name=excluded.name,
                category_id=excluded.category_id,
                parent_id=excluded.parent_id,
                region_id=excluded.region_id,
                shop_id=excluded.shop_id,
                store_id=excluded.store_id,
                server_clerk_id=excluded.server_clerk_id,
                qr_url=excluded.qr_url,
                type=excluded.type,
                capacity=excluded.capacity,
                sort=excluded.sort,
                status=excluded.status,
                is_use=excluded.is_use,
                is_delete=excluded.is_delete,
                create_time=excluded.create_time,
                updated_at=CURRENT_TIMESTAMP`

            for (const r of rows) {
                dbUtils.execute(sql, [
                    r.id, r.name, r.category_id, r.parent_id, r.region_id, r.shop_id, r.store_id, r.server_clerk_id,
                    r.qr_url, r.type, r.capacity, r.sort, r.status, r.is_use, r.is_delete, r.create_time
                ])
            }
        })
    },

    list(): StoreShopDesk[] {
        return dbUtils.query(`SELECT * FROM store_shop_desk ORDER BY sort ASC, name ASC`) as StoreShopDesk[]
    },

    getById(id: string): StoreShopDesk | null {
        const row = dbUtils.queryOne(`SELECT * FROM store_shop_desk WHERE id = ?`, [id])
        return row || null
    },

    deleteByIds(ids: string[]): void {
        if (!ids || ids.length === 0) return
        const placeholders = ids.map(() => '?').join(',')
        dbUtils.execute(`DELETE FROM store_shop_desk WHERE id IN (${placeholders})`, ids)
    }
}

export default storeShopDeskRepository


